package com.jacky.webflux.commons;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jacky.webflux.exceptions.CommonException;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class GlobalErrorWebExceptionHandler implements ErrorWebExceptionHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalErrorWebExceptionHandler.class);

    @SneakyThrows
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);

        if (ex instanceof CommonException ce) {
            BasicResp<String> nullResp = BasicResp.fail(ce.getCode(), ce.getMsg());
            byte[] bytes = new ObjectMapper().writeValueAsBytes(nullResp);
            DataBuffer wrap = response.bufferFactory().wrap(bytes);
            return response.writeWith(Mono.just(wrap));
        }
        BasicResp<String> nullResp = BasicResp.fail(103, "程序发生异常");
        byte[] bytes = new ObjectMapper().writeValueAsBytes(nullResp);
        DataBuffer wrap = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(wrap));
    }
}
